package com.kitty.game.welfare.service;

import com.kitty.game.role.model.Role;
import com.kitty.game.config.TaskSet;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.reward.model.RewardSet;
import com.kitty.game.reward.service.RewardService;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.welfare.WelfareDataPool;
import com.kitty.mina.message.MessagePusher;
import org.nutz.json.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Map;

@Component
public class FirstPayRewardHandler {
    @Autowired
    RewardService rewardService;
    private static final String FETCH_AFTER_TASK = "需要完成{0}任务才能领取";

    public void loadCommonSet(Map<String, String> commonSetMap) {
        RewardSet rewardSet = Json.fromJson(RewardSet.class, commonSetMap.get("first_pay_reward_set"));
        int firstPayFetchAfterTaskId = Integer.parseInt(commonSetMap.get("first_pay_fetch_after_taskid").trim());

        WelfareDataPool.firstPayRewardSet = rewardSet;
        WelfareDataPool.firstPayFetchAfterTaskId = firstPayFetchAfterTaskId;
    }

    /**处理首充*/
    public void handleFirstPay(Role role, int money, int addGold) {
        if (role == null) {return ;}

        /**第一次充值*/
        if (role.getFirstPayStatus() == 0) {
            role.setFirstPayStatus((byte) 1);
            role.save();
        }
    }

    /**领取首充奖励*/
    public void fetchReward(Role role) {
        /**未完成领取守护任务时不能领取首充奖励*/
        if (!role.getTask().isFinished(WelfareDataPool.firstPayFetchAfterTaskId)) {
            TaskSet taskSet = SpringUtils.getTaskService().getTaskSet(WelfareDataPool.firstPayFetchAfterTaskId, role);
            String msg = MessageFormat.format(FETCH_AFTER_TASK, taskSet.getTaskName());
            MessagePusher.pushMessage(role, new RespMsg(msg));
            return ;
        }

        if (canFetchReward(role) == false) {
            return ;
        }

        /**判断能否给奖励*/
        if (!rewardService.checkAddReward(role, WelfareDataPool.firstPayRewardSet)) {
            return ;
        }

        /**设置已经领取*/
        role.setFirstPayStatus((byte) 2);
        role.save();

        rewardService.addReward(role, WelfareDataPool.firstPayRewardSet);
    }

    /**是否可以领取奖励*/
    private boolean canFetchReward(Role role) {
        return role.getFirstPayStatus() == 1;
    }
}
